package top.hmtools;

import java.net.URL;
import java.util.Arrays;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import top.hmtools.configuration.GMConfiguration;

/**
 * 这是本软件的主入口,要运行本软件请直接运行本类就可以了
 */
@ComponentScan
public class AppMain extends Application {

	private static final Logger logger = LoggerFactory.getLogger(AppMain.class);

	private static ConfigurableApplicationContext context;

	@Override
	public void start(Stage stage) throws Exception {
		URL url = Thread.currentThread().getContextClassLoader().getResource("viewFxml/Index.fxml");
		FXMLLoader fxmlLoader = new FXMLLoader(url);
		
		Parent root = fxmlLoader.load();
		Scene scene = new Scene(root);
		
		GMContext.setPrimaryStage(stage);
		stage.getIcons().add(new Image(Thread.currentThread().getContextClassLoader().getResourceAsStream("images/cat_ghost.png")));
		stage.setResizable(true);
		stage.setScene(scene);
		stage.setTitle("hm-tools之mybatis反向生成工具");
		stage.setMaximized(true);
		stage.show();
	}

	@Override
	public void stop() throws Exception {
		if(context!=null){
			context.close();//关闭spring容器
		}
		logger.info("应用关闭。。。谢谢使用，再见~~");
		super.stop();
	}

	public static void main(String[] args) {
		String version = System.getProperty("java.version");

		logger.info("嗨啵的mybatis反向工具启动开始，当前Java版本号为：" + version);
		logger.info("启动参数有：" + Arrays.toString(args));

		if (Integer.parseInt(version.substring(2, 3)) >= 8 && Integer.parseInt(version.substring(6)) >= 60) {
			// 注解方式启动spring framework
			context = new AnnotationConfigApplicationContext(AppMain.class);

			// 获取全局配置对象实例，并加载配置文件内容
			GMConfiguration gmConfiguration = context.getBean(GMConfiguration.class);
			gmConfiguration.loadProperties(null);

			// 打印所有被注册的bean
			String[] beanNames = context.getBeanDefinitionNames();
			logger.info("本项目容器中的对象实例有：");
			for (String beanname : beanNames) {
				Object bean = context.getBean(beanname);
				logger.info(beanname+" ‘s hashcode is："+bean.hashCode());
				
			}

			// 启动JavaFX
			launch(args);
		} else {
			JFrame jFrame = new JFrame("版本错误");
			jFrame.setSize(500, 100);
			jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			JPanel jPanel = new JPanel();
			JLabel jLabel = new JLabel("JDK的版本不能低于1.8.0.60，请升级至最近的JDK 1.8再运行此软件");
			jPanel.add(jLabel);
			jFrame.add(jPanel);
			jFrame.setLocationRelativeTo(null);
			jFrame.setVisible(true);

		}
	}

}
